package org.swingDemo.UI.panel;

import net.miginfocom.swing.MigLayout;
import org.swingDemo.UI.MainFrame;
import org.swingDemo.entity.PageInfo;
import org.swingDemo.util.IconUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FolderContentPanel extends JPanel implements PropertyChangeListener {

    private final String[] ImageFileExts = {"jpg", "jpeg", "gif", "png"};
    private final int Image_Panel_Min_Width = 100;
    private final int Image_Panel_Min_Height = 150;
    private final int Image_Panel_Max_Width = 200;
    private final int Image_Panel_Max_Height = 300;

    private final int PAGE_SIZE = 8;

    private JPanel contentPanel;
    private PagePanel pagePanel;

    private List<File> fileList = new ArrayList<>();

    public FolderContentPanel() {
        initPanel();
    }

    private void initPanel() {
        contentPanel = new JPanel(new MigLayout("fill, wrap 4",
                "[center][center][center][center]"));
        pagePanel = new PagePanel();
        pagePanel.addPropertyChangeListener(this);
        this.setLayout(new BorderLayout());
        this.add(new JScrollPane(contentPanel), BorderLayout.CENTER);
        this.add(pagePanel, BorderLayout.PAGE_END);
    }

    private boolean isImageFile(File file) {
        final String fileName = file.getName();
        for (String ext : ImageFileExts) {
            if (fileName.toLowerCase().endsWith(ext)) {
                return true;
            }
        }
        return false;
    }

    private void filterSubFolderAndImageFiles(File folder) {
        fileList.clear();
        fileList.add(null);
        // 过滤目录内的文件(只显示文件夹与图片类型的文件)
        final File[] matchedFiles = folder.listFiles(file ->  file.isDirectory() || isImageFile(file));
        if (matchedFiles == null) {
            return;
        }
        final List<File> sortedFileList = Arrays.stream(matchedFiles).sorted((leftFile, rightFile) -> {
            boolean leftIsDirectory = leftFile.isDirectory();
            boolean rightIsDirectory = rightFile.isDirectory();
            final String leftFileName = leftFile.getName();
            final String rightFileName = rightFile.getName();
            if (leftIsDirectory == rightIsDirectory) {
                return leftFileName.compareTo(rightFileName);
            } else {
                return leftIsDirectory ? -1 : 1;
            }
        }).collect(Collectors.toList());

        fileList.addAll(sortedFileList);
    }

    private void dbClickImagePanel(File file, List<File> fileList) {
        if (file == null) {
            MainFrame.mainFrame.openParentFolder();
        } else if (file.isDirectory()) {
            MainFrame.mainFrame.openSubFolder(file);
        } else {
            // 过滤掉目录文件
            final List<File> imageFileList = fileList.stream()
                    .filter(file1 -> file1 != null && !file1.isDirectory())
                    .collect(Collectors.toList());
            MainFrame.mainFrame.operateImage(file, imageFileList);
        }
    }

    public void refreshPanel(File folder) {
        filterSubFolderAndImageFiles(folder);
        PageInfo pageInfo = new PageInfo(fileList.size(), PAGE_SIZE);
        pagePanel.setPageInfo(pageInfo);

        handlePageChanged();
    }

    public void handlePageChanged() {
        contentPanel.removeAll();

        PageInfo pageInfo = pagePanel.getPageInfo();
        List<File> filterList = fileList.stream().skip(pageInfo.getStart()).limit(PAGE_SIZE).collect(Collectors.toList());

        for (File file : filterList) {
            ImagePanel imagePanel;
            if (file == null) {
                imagePanel = new ImagePanel(IconUtil.FolderIcon.getImage(), "上一级");
            } else {
                imagePanel = new ImagePanel(file);
            }
            imagePanel.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
                        dbClickImagePanel(file, fileList);
                    }
                }
            });
            addCell2Tablelayout(imagePanel);
        }
        contentPanel.repaint();
    }

    private void addCell2Tablelayout(Component component) {
        String constraints = String.format("wmin %d, wmax %d, hmin %d, hmax %d",
                Image_Panel_Min_Width, Image_Panel_Max_Width,
                Image_Panel_Min_Height, Image_Panel_Max_Height);
        contentPanel.add(component, constraints);
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        String propertyName = evt.getPropertyName();
        if (propertyName.equals("page_changed")) {
            handlePageChanged();
        }
    }
}
